package cn.zd.demo1;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.navigation.ui.AppBarConfiguration;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


public class ActivityForwdBackActivity extends AppCompatActivity implements View.OnClickListener {

    private AppBarConfiguration appBarConfiguration;
    private TextView textView;
    private TextView tv_result;
    private AtomicInteger count = new AtomicInteger(0);
    private Button button_null;
    private Button button;
    private Button btn_incre;
    private Button btn_loaddemo0;
    private Button btn_loaddemo0_sys;
    private Button btn_loadtext;
    private ActivityResultLauncher<Intent> register;

    /**
     * 创建活动，将页面布局加载进内存，进入初始状态
     * @param savedInstanceState If the activity is being re-initialized after
     *     previously being shut down then this Bundle contains the data it most
     *     recently supplied in {@link #onSaveInstanceState}.  <b><i>Note: Otherwise it is null.</i></b>
     *
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Toast.makeText(this,this.getClass().getName(),Toast.LENGTH_LONG).show();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity_forwd_back);
        Toast.makeText(this,"版本："+ Build.VERSION.SDK,Toast.LENGTH_LONG).show();
        textView = findViewById(R.id.main_title);
        tv_result = findViewById(R.id.tv_result);
        tv_result.setText("应用名"+getString(R.string.app_name));
        textView.setText("点击按钮开始测试吧");
        btn_incre = findViewById(R.id.btn_incre);
        btn_incre.setOnClickListener(this);
        button = findViewById(R.id.btn_to_tab);
        button.setOnClickListener(this);
        btn_loaddemo0 = findViewById(R.id.btn_loaddemo0);
        btn_loaddemo0.setOnClickListener(this);
        btn_loaddemo0_sys = findViewById(R.id.btn_loaddemo0_sys);
        btn_loaddemo0_sys.setOnClickListener(this);
        btn_loadtext = findViewById(R.id.btn_loadtext);
        btn_loadtext.setOnClickListener(this);
        button_null = findViewById(R.id.btn_null);
        button_null.setOnClickListener(this);
        ActivityForwdBackActivity that = this;
        findViewById(R.id.btn_loadapp).setOnClickListener(this);
        findViewById(R.id.btn_call).setOnClickListener(this);
        // 获取元数据
        TextView tv_metadata = findViewById(R.id.tv_metadata);
        try {
            ActivityInfo activityInfo = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);
            tv_metadata.setText("获取到的元数据："+activityInfo.metaData.getString("metatest"));

        } catch (PackageManager.NameNotFoundException e) {
            Log.i("PK","获取元数据出错了！");
        }
        // 注册结果处理的回调
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            // 上一个activity 完成后回调这里
            @Override
            public void onActivityResult(ActivityResult result) {
                Intent data = result.getData();
                Bundle extras = data.getExtras();
                Toast.makeText(that,"接收完成数据："+ extras.getInt("count"),Toast.LENGTH_LONG).show();
                tv_result.setText("接收到的数据："+extras.getInt("count"));
            }
        });
        Toast.makeText(this,"onCreate！",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View view) {

        Log.i("MainActivity","按钮被点击了,应用名"+getString(R.string.app_name));
        Toast.makeText(this,"按钮被点击了！"+ ((Button)view).getText(),Toast.LENGTH_LONG).show();

        if(view.getId() == btn_incre.getId() ){
            count.incrementAndGet();
            textView.setText("点击次数:"+count.get());
            Toast.makeText(this,"功德 +1！",Toast.LENGTH_LONG).show();
        }else if(view.getId() == button.getId() ){
            Intent intent = new Intent(this, ActivityBackActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("count",count.get());
            intent.putExtras(bundle);
//            startActivity(intent);
            Toast.makeText(this,"显式Intent构造方法调用",Toast.LENGTH_LONG).show();
            register.launch(intent);
        } else if (view.getId() == R.id.btn_loadapp){
            // 获取所有的包和类名
            PackageManager packageManager = getPackageManager();
            List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(0);

            String calendarPackageName = null;
            String calendarClassName = null;
            for (ApplicationInfo applicationInfo : installedApplications) {
                String packageName = applicationInfo.packageName;
                String className = null;

                try {
                    PackageInfo packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
                    ActivityInfo[] activities = packageInfo.activities;

                    if (activities != null && activities.length > 0) {
                        className = activities[0].name;
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                if(packageName.indexOf("calendar") > -1) {
                    calendarPackageName = packageName;
                    calendarClassName = className;
                }
                Log.d("PackageInfo", "Package Name: " + packageName + ", Class Name: " + className);
            }

            Intent intent = new Intent();
            ComponentName component = new ComponentName(calendarPackageName,calendarClassName);

            intent.setComponent(component);
            Toast.makeText(this,"显式Intent setComponent方法调用",Toast.LENGTH_LONG).show();
            startActivity(intent);
        } else if(view.getId() == R.id.btn_call){
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_DIAL);
            Uri uri = Uri.parse("tel:123456");
            intent.setData(uri);
            Toast.makeText(this,"隐式Intent setAction(系统动作常量名)方法调用",Toast.LENGTH_LONG).show();
            startActivity(intent);
        }else if(view.getId() == R.id.btn_loaddemo0){
            Intent intent = new Intent();
            Toast.makeText(this,"显式Intent setComponent方法调用",Toast.LENGTH_LONG).show();
            ComponentName component = new ComponentName("cn.zd.demo0","cn.zd.demo0.DemoActivity");
            intent.setComponent(component);
            startActivity(intent);
        }else if(view.getId() == R.id.btn_loaddemo0_sys){
            Intent intent = new Intent();
            intent.setAction("android.intent.action.DEMO0");
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            Toast.makeText(this,"隐式Intent setAction(系统动作常量名)、addCategory方法调用",Toast.LENGTH_LONG).show();
            startActivity(intent);
        }else if(view.getId() == R.id.btn_loadtext){
            Intent intent = new Intent();
            Toast.makeText(this,"显式Intent setClass方法调用",Toast.LENGTH_LONG).show();
            intent.setClass(this,TextViewsActivity.class);
            startActivity(intent);
        }else {
            Toast toast = Toast.makeText(this, "点我没有用", Toast.LENGTH_LONG);
            toast.show();
        }
    }

    /**
     * 销毁活动，回收活动占用的资源，页面从内存中清除
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"onDestroy！",Toast.LENGTH_LONG).show();
    }

    /**
     * 开始活动，将页面显示在屏幕上 进入就绪状态
     */
    @Override
    protected void onStart() {
        super.onStart();
        Toast.makeText(this,"onStart！",Toast.LENGTH_LONG).show();
    }

    /**
     * 停止活动，页面将不在屏幕中显示
     */
    @Override
    protected void onStop() {
        super.onStop();
        Toast.makeText(this,"onStop！",Toast.LENGTH_LONG).show();
    }

    /**
     * 恢复活动  活动页面进入活跃状态，能够与用户交互，如允许用户点击、输入等
     */
    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(this,"onResume！",Toast.LENGTH_LONG).show();
    }

    /**
     * 暂停活动，页面进入暂停状态，无法与用户正常交互
     */
    @Override
    protected void onPause() {
        super.onPause();
        Toast.makeText(this,"onPause！",Toast.LENGTH_LONG).show();
    }

    /**
     * 重用已有实例
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Toast.makeText(this,"onNewIntent！",Toast.LENGTH_LONG).show();
    }

    /**
     * 重启活动 重新加载内存中的页面数据
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        Toast.makeText(this,"onRestart！",Toast.LENGTH_LONG).show();
    }

}